#pragma once

#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class ServerCal
{
public:
    ServerCal()
    {
    }

    // 计算机计算的报文结果返回
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
        {
            if (req.y == 0)
                resp.code = Div_Zero;
            else
                resp.result = req.x / req.y;
        }
        break;
        case '%':
        {
            if (req.y == 0)
                resp.code = Mod_Zero;
            else
                resp.result = req.x % req.y;
        }
        break;
        default:
            resp.code = Other_Oper;
            break;
        }

        return resp;
    }

    // 网络计算机  "len"\n"10 + 20"\n
    std::string Calculator(std::string &package)
    {
        // 序列化报文
        std::string content;
        // "len"\n"10 + 20"\n
        bool r = Decode(package, &content); // 拿到报文
        if (!r)                             // 如果报文有问题就直接返回
            return "";

        // "10 + 20"
        Request req;
        // "10 + 20" -> x=10 op=+ y=20
        r = req.Deserialize(content); // 反序列化报文
        if (!r)                       // 同样有问题就直接返回
            return "";

        content = ""; // 将要返回的结果报文
        // result=30 code=0;
        Response resp = CalculatorHelper(req); // 进行结果计算
        // "30 0"
        resp.Serialize(&content);              // 序列化封装报文
        // "len"\n"30 0"
        content = Encode(content);             // 返回封装后的报文

        return content;
    }

    ~ServerCal()
    {
    }
};